<?php
/*
 * Created on Aug 30, 2012
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

include_once("constant/AffiliateClass.php");


class CjApi
{
	private $websiteId   	= '5603849';
	private $auth;
	
	private $linkSearchUrl 			= 'https://linksearch.api.cj.com/v2/link-search?';
	private $advertiserLookupUrl 	= 'https://advertiser-lookup.api.cj.com/v3/advertiser-lookup?';

	
	public function __construct()
	{
		$this->auth = stream_context_create(
			array(
			'http' => array(
				'method' => 'GET',
				'header' => 'Authorization: ' . // USE YOUR OWN.
					'0087f2c6b984b201b64fa9ecb3bef3d3500092c751fb0482d8869c7f5b5a4eb53e0df7b9037b4c12af5c2bc659d1896ee369c86e52200415a91b3902a10ff9f34f' .
					'/41430d9d1f93687901933c3b298ed9414d9528b435417c22bfb43efb36c61400ea251bf07fa1851f4eb1230d8c5f1512456f3dd6413c0b6120d54dd49d240919'
				)
			));
	}
	
	private function getAdvertiserXml($maxResults = 100, $pageNumber = 1, $advertiserIds = '', $advertiserName = '', $keywords = '', $mobileTrackingCertified = '')
	{
	    // Get the results
	    $url = $this->advertiserLookupUrl;
	    
	   	if(!empty($pageNumber)){
	    	$url .= '&page-number=' . $pageNumber;
	    }
	    
	    if(empty($maxResults) || $maxResults > 100){
	    	$url .= '&records-per-page=100';
	    }else{
	    	$url .= '&records-per-page=' . $maxResults;
	    }		    
	    
	    if(!empty($createDateMax)){
	    	$url .= "&keywords=$keywords";
	    }	    
	    
	    if(!empty($advertiserIds)){
	    	$url .= '&advertiser-ids=' . $advertiserIds;
	    }
	    
	    if(!empty($advertiserName)){
	    	$url .= '&advertiser-name=' . $advertiserName;
	    }
	    
	    if(!empty($mobileTrackingCertified)){
	    	$url .= '&mobile-tracking-certified=' . $mobileTrackingCertified;
	    }
	    
	    if(!empty($promotionEndDate)){
	    	$url .= '&promotion-end-date=' . $promotionEndDate;
	    }
	    

		echo "cj URL = $url";
		echo "\n";
		
	 
	    $content = file_get_contents($url, false, $this->auth);
	    
//		print_r($content);
		
		$response = new SimpleXMLElement($content);
			
		return $response;		
	}
	
	public function getAdvertisers($maxResults = 100, $pageCount = 1, $advertiserIds = '', $advertiserNameParam = '', $keywords = '', $mobileTrackingCertified = '')
	{
		$pageNumber 	= 1;
		$xmlData 		= $this->getAdvertiserXml($maxResults, $pageNumber, $advertiserIds, $advertiserNameParam, $keywords, $mobileTrackingCertified);
		$advers 		= array();
		
//		print_r($xmlData);
		
		
		$adversNodes = $xmlData->xpath('/cj-api/advertisers');
		
		$total 				= 0;
		$totalPages 		= 0;
		$recordsReturned 	= 0;
		$pageNumber			= 0;
		
		foreach ($adversNodes as $adverNode) {
			$arrAttr = $adverNode->attributes();
			
			$total 				= $arrAttr['total-matched'];
			$recordsReturned 	= $arrAttr['records-returned'];
			$pageNumber 		= $arrAttr['page-number'];
		}
		
		$totalPages = ceil($total / $maxResults);
		
		if($pageCount > $totalPages)
			$pageCount = $totalPages;
			
		echo "page: ". $totalPages . "\n";
		echo "recordsReturned: ". $recordsReturned . "\n";
		echo "pageNumber: ". $pageNumber . "\n";
		
		while(true){	
			$dataNodes = $xmlData->xpath('/cj-api/advertisers/advertiser');
			
			foreach($dataNodes as $adver){
//				echo "-----------------------------------\n";
				
				$advertiserId			= (string)$adver->{'advertiser-id'};
			    $advertiserName			= (string)$adver->{'advertiser-name'};
			    $accountStatus			= (string)$adver->{'account-status'};
			    $programUrl				= (string)$adver->{'program-url'};
			
		     	$mobileTrackingCertified= (string)$adver->{'mobile-tracking-certified'};
			    $language				= (string)$adver->language;
			    
			    $networkRank			= (string)$adver->{'network-rank'};
			    $primaryCategory		= $adver->{'primary-category'};
			    $performanceIncentives	= (string)$adver->{'performance-incentives'};
			    $actions				= $adver->{'actions'};
			    $linkTypes				= $adver->{'link-types'};
			    $relationshipStatus		= (string)$adver->{'relationship-status'};
			    $sevenDayEpc			= (string)$adver->{'seven-day-epc'};
			    $threeMonthEpc			= (string)$adver->{'three-month-epc'};
    
			    $oData = new AdvertiserCJ();
			    
			    $oData->advertiserId			= $advertiserId;
			    $oData->advertiserName			= $advertiserName;
			    $oData->accountStatus			= $accountStatus;
			    $oData->programUrl				= $programUrl;
			    $oData->mobileTrackingCertified	= $mobileTrackingCertified;
			
			    $oData->networkRank				= $networkRank;                
			    $oData->language				= $language;
			    
			    $oData->primaryCategory			= $primaryCategory;
			    $oData->performanceIncentives	= $performanceIncentives;   
			    $oData->actions					= $actions;               
			    $oData->linkTypes				= $linkTypes;            
			    $oData->relationshipStatus		= $relationshipStatus;          
			    $oData->sevenDayEpc				= $sevenDayEpc;
			    $oData->threeMonthEpc			= $threeMonthEpc;
			    
    			$advers[] = $oData;    			
    			
//			    echo "advertiser-id: ". $advertiserId . "\n";
//			    echo "advertiser-name: ". $advertiserName . "\n";
//			    echo "accountStatus: ". $accountStatus . "\n";
//			    echo "programUrl: ". $programUrl . "\n";
//			    echo "mobileTrackingCertified: ". $mobileTrackingCertified . "\n";
//			    echo "networkRank: ". $networkRank . "\n";
//			    echo "language: ". $language . "\n";
//			    echo "primaryCategory: ". $primaryCategory . "\n";
//			    echo "performanceIncentives: ". $performanceIncentives . "\n";
//			    echo "actions: ". $actions . "\n";
//			    echo "linkTypes: ". $linkTypes . "\n";
//			    echo "relationshipStatus: ". $relationshipStatus . "\n";
//			    echo "threeMonthEpc: ". $threeMonthEpc . "\n";
//			    echo "sevenDayEpc: ". $sevenDayEpc . "\n";
//			    
//			    echo "display category\n";
////			    $oData->getPrimaryCategories();
//		    	print_r($oData->getActions());
			}
			
			$pageNumber += 1;
			if($pageNumber > $pageCount)
				break;
				
			$xmlData = $this->getAdvertiserXml($maxResults, $pageNumber, $advertiserIds, $advertiserNameParam, $keywords, $mobileTrackingCertified);
		};
		
		return $advers;
	}
	
	private function getLinksXml($maxResults = 100, $pageNumber = 1, $advertiserIds = 'joined', $promotionStartDate = '', $promotionEndDate = '', $promotionType = 'coupon', $keywords = '', $category = '', $linkType = '')
	{
	    // Get the results
	    $url = $this->linkSearchUrl . 'website-id=' . $this->websiteId;
	    
	    	    
	    if(!empty($advertiserIds)){
	    	$url .= '&advertiser-ids=' . $advertiserIds;
	    }
	    
	    if(empty($maxResults) || $maxResults > 100){
	    	$url .= '&records-per-page=100';
	    }else{
	    	$url .= '&records-per-page=' . $maxResults;
	    }		    
	    
	    if(!empty($promotionType)){
	    	$url .= "&promotion-type=" . urlencode($promotionType);
	    }
	    
	    if(!empty($createDateMax)){
	    	$url .= "&keywords=$keywords";
	    }
	    
	    if(!empty($pageNumber)){
	    	$url .= '&page-number=' . $pageNumber;
	    }
	    
	    if(!empty($category)){
	    	$url .= '&category=' . $category;
	    }
	    
	    if(!empty($linkType)){
	    	$url .= '&link-type=' . $linkType;
	    }
	    
	    if(!empty($promotionStartDate)){
	    	$url .= '&promotion-start-date=' . $promotionStartDate;
	    }
	    
	    if(!empty($promotionEndDate)){
	    	$url .= '&promotion-end-date=' . $promotionEndDate;
	    }
	    		
		echo "cj URL = $url";
		echo "\n";
		
	 	
	    $content = file_get_contents($url, false, $this->auth);
	    
//		print_r($content);
		
		$response = new SimpleXMLElement($content);
			
		return $response;		
	}
	
	public function getLinks($maxResults = 100, $pageCount = 1, $advertiserIds = 'joined', $promotionStartDateParam = '', $promotionEndDateParam = '', $promotionTypeParam = 'coupon', $keywords = '', $categoryParam = '', $linkTypeParam = '')
	{
		$pageNumber 	= 1;
		$xmlData 		= $this->getLinksXml($maxResults, $pageNumber, $advertiserIds, $promotionStartDateParam, $promotionEndDateParam, $promotionTypeParam, $keywords, $categoryParam, $linkTypeParam);
		$links 			= array();
		
//		print_r($xmlData);
		
		
		$linksNodes = $xmlData->xpath('/cj-api/links');
		
		$total				= 0;
		$totalPages 		= 0;
		$recordsReturned 	= 0;
		$pageNumber			= 0;
		
		foreach ($linksNodes as $linksNode) {
			$arrAttr = $linksNode->attributes();
			
			$total 				= $arrAttr['total-matched'];
			$recordsReturned 	= $arrAttr['records-returned'];
			$pageNumber 		= $arrAttr['page-number'];
		}
		
		$totalPages = ceil($total / $maxResults);
		if($pageCount > $totalPages)
			$pageCount = $totalPages;
		
		echo "page: ". $totalPages . "\n";
		echo "recordsReturned: ". $recordsReturned . "\n";
		echo "pageNumber: ". $pageNumber . "\n";
		
		while(true){	
			$linkNodes = $xmlData->xpath('/cj-api/links/link');
			
			foreach($linkNodes as $link){
//				echo "-----------------------------------\n";
				
				$advertiserId			= (string)$link->{'advertiser-id'};
			    $advertiserName			= (string)$link->{'advertiser-name'};
			    $category				= (string)$link->category;
			    $clickCommission		= (string)$link->{'click-commission'};
			    $creativeHeight			= (string)$link->{'creative-height'};
			
		     	$creativeWidth			= (string)$link->{'creative-width'};
			    $language				= (string)$link->language;
			    
			    $linkCodeHtml			= (string)$link->{'link-code-html'};
			    $linkCodeJavascript		= (string)$link->{'link-code-javascript'};
			    $description			= (string)$link->{'description'};
			    $destination			= (string)$link->{'destination'};
			    $linkId					= (string)$link->{'link-id'};
			    $linkName				= (string)$link->{'link-name'};
			    $linkType				= (string)$link->{'link-type'};
			    
			    $performanceIncentive	= (string)$link->{'performance-incentive'};
			    $promotionEndDate		= (string)$link->{'promotion-end-date'};
			    $promotionStartDate		= (string)$link->{'promotion-start-date'};
			    $promotionType			= (string)$link->{'promotion-type'};
			    
			    $relationshipStatus		= (string)$link->{'relationship-status'};
			    $saleCommission			= (string)$link->{'sale-commission'};
			    $sevenDayEpc			= (string)$link->{'seven-day-epc'};
			    $threeMonthEpc			= (string)$link->{'three-month-epc'};
			    
			    $oData = new LinkCJ();
			    
			    $oData->advertiserId		= $advertiserId;
			    $oData->advertiserName		= $advertiserName;           		// advertiser-name
			    $oData->category			= $category;                     	// category
			    $oData->clickCommission		= $clickCommission;                // click-commission
			    $oData->creativeHeight		= $creativeHeight;                 // creative-height
			
			    $oData->creativeWidth		= $creativeWidth;                 	// creative-width
			    $oData->language			= $language;                 		// language
			    
			    $oData->linkCodeHtml		= $linkCodeHtml;                 	// link-code-html
			    $oData->linkCodeJavascript	= $linkCodeJavascript;             // link-code-javascript
			    $oData->description			= $description;                 	// description
			    $oData->destination			= $destination;                 	// destination
			    $oData->linkId				= $linkId;                 		// link-id
			    $oData->linkName			= $linkName;                 		// link-name
			    $oData->linkType			= $linkType;                 		// link-type
			    
			    $oData->performanceIncentive= $performanceIncentive;           // performance-incentive
			    $oData->promotionEndDate	= $promotionEndDate;               // promotion-end-date
			    $oData->promotionStartDate	= $promotionStartDate;             // promotion-start-date
			    $oData->promotionType		= $promotionType;                 	// promotion-type
			    
			    $oData->relationshipStatus	= $relationshipStatus;             // relationship-status
			    $oData->saleCommission		= $saleCommission;                 // sale-commission
			    $oData->sevenDayEpc			= $sevenDayEpc;                 	// seven-day-epc
			    $oData->threeMonthEpc		= $threeMonthEpc; 
    
    			$links[] = $oData;
 
// if(!empty($promotionType))  {			
//    			echo "----------------------------------------------\n";
//    			
//			    echo "advertiser-id: ". $advertiserId . "\n";
//			    echo "advertiser-name: ". $advertiserName . "\n";
//			    echo "category: ". $category . "\n";
////			    echo "clickCommission: ". $clickCommission . "\n";
//			    echo "creativeHeight: ". $creativeHeight . "\n";
//			    echo "creativeWidth: ". $creativeWidth . "\n";
////			    echo "language: ". $language . "\n";
//			    echo "linkCodeHtml: ". $linkCodeHtml . "\n";
//			    echo "linkCodeJavascript: ". $linkCodeJavascript . "\n";
//			    echo "description: ". $description . "\n";
//			    echo "destination: ". $destination . "\n";
//			    echo "linkId: ". $linkId . "\n";
//			    echo "linkName: ". $linkName . "\n";
//			    echo "linkType: ". $linkType . "\n";
//			    echo "performanceIncentive: ". $performanceIncentive . "\n";
//			    echo "promotionEndDate: ". $promotionEndDate . "\n";
//			    echo "promotionStartDate: ". $promotionStartDate . "\n";
//			    echo "promotionType: ". $promotionType . "\n";
////			    echo "relationshipStatus: ". $relationshipStatus . "\n";
//			    echo "saleCommission: ". $saleCommission . "\n";
//			    echo "sevenDayEpc: ". $sevenDayEpc . "\n";
//
//				echo "getTrackingUrl: ". $oData->getTrackingUrl() . "\n";
//		    	echo "getBannerUrl: ". $oData->getBannerUrl() . "\n";
//		    	echo "getImpressionPixelUrl: ". $oData->getImpressionPixelUrl() . "\n";
//		    	
//		    	
//		    	echo "getFilterName: ". $oData->getFilterName() . "\n";
//		    	echo "getFilterDescription: ". $oData->getFilterDescription() . "\n";
//		    	echo "getCode: ". $oData->getCode() . "\n";
// }		    	
		    	
		    	
			}
			
			$pageNumber += 1;
			if($pageNumber > $pageCount)
				break;
				
			$xmlData = $this->getLinksXml($maxResults, $pageNumber, $advertiserIds, $promotionStartDateParam, $promotionEndDateParam, $promotionTypeParam, $keywords, $categoryParam, $linkTypeParam);
		};
		
		return $links;
	}
	

}
?>
